<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Pc_Api_Standard_Order extends Controller_Pc_Api_Base
{
    public function before()
    {
        parent::before();
    }

    /*
    * 获取订单状态列表
    */
    public function action_get_status_list()
    {
        $result = Model_Api_Standard_Order::get_status_list();
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);

    }

    /*
    * 获取订单支付类型列表
    */
    public function action_get_paytype_list()
    {
        $result = Model_Api_Standard_Order::get_paytype_list();
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);

    }

    public function action_search()
    {
        $condition = array();
        $condition['typeid'] = Common::remove_xss($this->request_body->content->model_type_id);
        $condition['status'] = Common::remove_xss($this->request_body->content->status);
        $condition['keyword'] = Common::remove_xss($this->request_body->content->keyword);
        $condition['paysource'] = Common::remove_xss($this->request_body->content->paysource);
        $condition['start_time'] = Common::remove_xss($this->request_body->content->start_time);
        $condition['end_time'] = Common::remove_xss($this->request_body->content->end_time);
        $condition['eticketno'] = Common::remove_xss($this->request_body->content->eticketno);
        $condition['memberid'] = Common::remove_xss($this->request_body->content->memberid);
        $condition['isconsume'] = Common::remove_xss($this->request_body->content->isconsume);
        $condition['webid'] = Common::remove_xss($this->request_body->content->webid);
        $condition['webid'] = (is_numeric($condition['webid']) ? $condition['webid'] : -1);

        $condition['start'] = Common::remove_xss($this->request_body->content->page->start);
        $condition['limit'] = Common::remove_xss($this->request_body->content->page->limit);
        $condition['sort'] = array();

        //拼接扩展typeid
        $tongyongtypeid=DB::select()
            ->from('xcx_nav')
            ->where('m_mode','=','tongyong')
            ->and_where('m_isopen','=',1)
            ->execute()->as_array();
        $tyArr = array();
        if(!empty($tongyongtypeid)){
            foreach ($tongyongtypeid as $key=>$vel){
                $str=explode('=',$vel['m_params']);
                array_push($tyArr,$str[1]);
            }
        }

        // 将通用产品添加到搜索列表项中
        $tystr = !empty($tyArr) ? ','.(implode(',',$tyArr)) : '';
        $condition['typeid']=$condition['typeid'].$tystr;
        if ($this->request_body->content->sort->property)
        {
            $condition['sort']['property'] = Common::remove_xss($this->request_body->content->sort->property);
            if ($this->request_body->content->sort->direction)
            {
                $condition['sort']['direction'] = Common::remove_xss($this->request_body->content->sort->direction);
            } else
            {
                $condition['sort']['direction'] = "asc";
            }
        }

        $result = Model_Api_Standard_Order::search($condition);

        //替换通用订单拼音
        if(!empty($result['data']) &&!empty($tyArr)){
            foreach ($result['data'] as $kr=>$vr)
            {
                if(in_array($vr['typeid'],$tyArr)){
                    $result['data'][$kr]['pinyin']='tongyong';
                }
            }
        }

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    public function action_get_detail()
    {
        $id = Common::remove_xss($this->request_body->content->id);

        $result = Model_Api_Standard_Order::get_detail($id);
        $result['totalprice'] = $result['totalprice'] - $result['iscoupon']['cmoney'] - $result['jifentprice'] - $result['platform_discount'] - $result['envelope_price'];
		
        if (empty($result))
        {
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key'], false, "查找订单信息失败", "查找订单信息失败");
        } else
        {
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }
    }
    public function action_xcx_traveller_list()
    {
        $orderid = $this->request_body->content->orderid;
        $userid = $this->request_body->content->userid;
        $list = DB::select()->from('member_order_tourer')->where('orderid','=',$orderid)->execute()->as_array();
        $this->send_datagrams($this->client_info['id'], $list, $this->client_info['secret_key']);
    }

    public function action_statistics_annual_report()
    {
        $year = Common::remove_xss($this->request_body->content->year);
        $model_type_id = Common::remove_xss($this->request_body->content->model_type_id);

        $current_year = date('Y');
        $year = empty($year) ? $current_year : $year;
        if ($year > $current_year)
        {
            $this->send_datagrams($this->client_info['id'], null, $this->client_info['secret_key'], false, "统计年份不能超过今年", "统计年份不能超过今年");
        }

        $result = Model_Api_Standard_Order::statistics_annual_report($year, $model_type_id);

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    public function action_statistics_monthly_report()
    {
        $model_type_id = Common::remove_xss($this->request_body->content->model_type_id);

        $result = Model_Api_Standard_Order::statistics_monthly_report($model_type_id);

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    public function action_change_status()
    {
        $id = Common::remove_xss($this->request_body->content->id);
        $result = Model_Api_Standard_Order::get_detail($id);
        $ordersn = $result['ordersn'];
        St_Payment::change_order($ordersn, '微信小程序');
        $out = array('status'=>1);
        $this->send_datagrams($this->client_info['id'], $out, $this->client_info['secret_key']);


    }
	
	public function action_cancelOrder()
	{
		$ordersn = Common::remove_xss($this->request_body->content->ordersn);
        $result = Model_Api_Standard_Order::cancelOrder($ordersn);
		$this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
	}

    /**
     * 申请退款
     */
    public function action_refund()
    {
        $ordersn = Common::remove_xss($this->request_body->content->ordersn);
        $userid = Common::remove_xss($this->request_body->content->userid);
        $data['ordersn'] = $ordersn;
        $data['platform'] = 'weixin';
        $data['refund_reason'] = '微信小程序申请退款';
        $data['alipay_account'] = 'userid:'.$userid;
        $result = Pay_Online_Refund::apply_order_refund($data,$userid,$this->get_model_class_name($ordersn));
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }
    /**
     * 取消申请退款
     */
    public function action_refund_back()
    {
        $ordersn = Common::remove_xss($this->request_body->content->ordersn);
        $userid = Common::remove_xss($this->request_body->content->userid);
        $result = Pay_Online_Refund::order_refund_back($ordersn,$userid,$this->get_model_class_name($ordersn));
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }
    //获取用户订单数量
    public function action_user_order()
    {
        $userid = Common::remove_xss($this->request_body->content->userid);

        $result = $this->get_user_order_count($userid);
        
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 保存微信支付信息 用户小程序退款
     */
    public function action_set_wxpay_data()
    {

        $data['appid'] = Common::remove_xss($this->request_body->content->appid);
        $data['mch_id'] = Common::remove_xss($this->request_body->content->mch_id);
        $data['transaction_id'] = Common::remove_xss($this->request_body->content->transaction_id);
        $out_trade_no = Common::remove_xss($this->request_body->content->out_trade_no);
        $data['out_trade_no'] = substr($out_trade_no , 0 , -4); // 去掉支付时添加的4位随机数
        $data['total_fee'] = Common::remove_xss($this->request_body->content->total_fee);
        $data['orderid'] = Common::remove_xss($this->request_body->content->orderid);
        $data['mch_key'] = Common::remove_xss($this->request_body->content->mch_key);

        $out = array('status'=>1);

        // 检查是否已经保存
        $res = DB::select()->from('xcx_wxpay_data')
            ->where("transaction_id","=",$data['transaction_id'])
            ->and_where("orderid","=",$data['orderid'])
            ->execute()->current();
        if($res)
        {
            $this->send_datagrams($this->client_info['id'], $out, $this->client_info['secret_key']);
        }
        //数据入库
        DB::insert('xcx_wxpay_data', array_keys($data))->values(array_values($data))->execute();

        //更改订单
        $online_transaction_no = json_encode(array('source'=>'wxxcx','transaction_no' => $data['transaction_id']));
        $order = array(
            'online_transaction_no' => $online_transaction_no,
        );
        $order_info = DB::select()->from('member_order')->where("id={$data['orderid']}")->execute()->current();
        if($order_info['need_confirm']==1){
            $order['ispay'] = 1;
            $order['status'] = 0;
        }
        DB::update('member_order')->where('id', '=', $data['orderid'])->set($order)->execute();

        $this->send_datagrams($this->client_info['id'], $out, $this->client_info['secret_key']);
    }

    private function get_model_class_name($ordersn)
    {
        $typeid = DB::select('typeid')->from('member_order')->where('ordersn','=',$ordersn)->execute()->get('typeid');
        $pinyin =DB::select('maintable')->from('model')->where('id','=',$typeid)->execute()->get('maintable');
        if(empty($pinyin))
        {
            return false;
        }
        return  'Model_'.ucfirst($pinyin);

    }


    public function get_user_order_count($userid)
    {
        $w = "memberid=$userid and (typeid !=21 or (typeid=21 && pid=0))";
        $list = DB::query(Database::SELECT, "select id,typeid,status,productautoid from sline_member_order  where {$w}")->execute()->as_array();
        $result = array();
        foreach($list as $k=>$v)
        {
            if(!empty($v))
            {
                $pinyin = DB::select('maintable')->from('model')->where('id','=',$v['typeid'])->execute()->get('maintable');
                $id = DB::select('id')->from($pinyin)->where('id','=',$v['productautoid'])->execute()->get('id');
                if(!empty($id))
                {
                    $result['count'][] = $v;
                }
                if(!empty($id) && $v['status']==1)
                {
                    $result['dfk'][] = $v;
                }
                if(!empty($id) && $v['status']==2)
                {
                    $result['dxf'][] = $v;
                }     
                if(!empty($id) && $v['status']==5)
                {
                    $result['ywc'][] = $v;
                }
                if(!empty($id) && $v['status']==6)
                {
                    $result['tkz'][] = $v;
                }
            }
        }
        $res['count']['num'] = count($result['count']) ;
        $res['dfk']['num'] = count($result['dfk']) ;
        $res['dxf']['num'] = count($result['dxf']) ;
        $res['ywc']['num'] = count($result['ywc']) ;
        $res['tkz']['num'] = count($result['tkz']) ;
        return $res;
    }

    // 确认消费
    public function action_consume_order()
    {

        $orderid = intval($this->request_body->content->orderid);
        $mid = intval($this->request_body->content->mid);
        $typeid = intval($this->request_body->content->typeid);

        if(!$orderid || !$mid)
        {
            $this->send_datagrams($this->client_info['id'], array('status'=> false, 'msg'=> '提交信息有误'), $this->client_info['secret_key']);
        }

        // 获取订单信息
        $info = DB::select()->from("member_order")->where("memberid","=",$mid)->and_where("id","=",$orderid)->execute()->current();
        if (empty($info))
        {
            $this->send_datagrams($this->client_info['id'],  array('status'=> false, 'msg'=> '查找订单信息失败'), $this->client_info['secret_key'], false, "查找订单信息失败", "查找订单信息失败");
        }
        else
        {
            if($info['status'] != 2)
            {
                $this->send_datagrams($this->client_info['id'], array('status'=> false, 'msg'=> '订单状态异常，请重试'), $this->client_info['secret_key']);
            }
            else
            {
                $data = array('status'=>5);
                $flag = DB::update('member_order')->set($data)->where('ordersn','=',$info['ordersn'])->execute();
                if($flag)
                {
                    $order = DB::select()->from('member_order')->where('ordersn', '=', $info['ordersn'])->execute()->current();
                    $model = Model_Api_Standard_Pub::get_model_class_name($typeid);
                    $status = Model_Member_Order::back_order_status_changed(2, $order, $model);
                    $result = array('status'=> $status, 'msg'=> $status ? '确认消费成功':'确认消费失败');
                }
                else
                {
                    $result = array('status'=> false, 'msg'=> '确认消费失败');
                }
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            }
        }
    }


}